﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Legend.Threading
{
    /// <summary>
    /// An adaptor to make the ReaderWriterLockSlim class adhere
    /// to the IReaderWriterLock-interface.
    /// </summary>
    public class ReaderWriterLockSlimAdapter
        : ISynchronizationManager
    {
        private ReaderWriterLockSlim readerWriterLock;

        /// <summary>
        /// Initializes a new instance of the <see cref="ReaderWriterLockSlimAdapter"/> class.
        /// </summary>
        /// <param name="readerWriterLock">The reader writer lock.</param>
        public ReaderWriterLockSlimAdapter(ReaderWriterLockSlim readerWriterLock)
        {
            Require.ThatArgument(readerWriterLock).Named("readerWriterLock").IsNotNull();
            this.readerWriterLock = readerWriterLock;
        }

        /// <summary>
        /// Enters the write lock.
        /// </summary>
        public void EnterWriteLock()
        {
            readerWriterLock.EnterWriteLock();
        }

        /// <summary>
        /// Exits the write lock.
        /// </summary>
        public void ExitWriteLock()
        {
            readerWriterLock.ExitWriteLock();
        }

        /// <summary>
        /// Enters the read lock.
        /// </summary>
        public void EnterReadLock()
        {
            readerWriterLock.EnterReadLock();
        }

        /// <summary>
        /// Exits the read lock.
        /// </summary>
        public void ExitReadLock()
        {
            readerWriterLock.ExitReadLock();
        }

        /// <summary>
        /// Exits an upgradable lock.
        /// </summary>
        public void EnterUpgradableReadLock()
        {
            readerWriterLock.EnterUpgradeableReadLock();
        }

        /// <summary>
        /// Enters a read lock that can be upgraded to a write lock later.
        /// </summary>
        public void ExitUpgradableReadLock()
        {
            readerWriterLock.ExitUpgradeableReadLock();
        }

        /// <summary>
        /// Gets the recursion policy set on the lock.
        /// </summary>
        /// <value></value>
        public System.Threading.LockRecursionPolicy RecursionPolicy
        {
            get 
            {
                return readerWriterLock.RecursionPolicy;
            }
        }

        /// <summary>
        /// Disposes the lock manager.
        /// </summary>
        public void Dispose()
        {
            readerWriterLock.Dispose();
        }
    }
}
